package com.xjrsoft.third;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.xjrsoft.common.result.Response;
import com.xjrsoft.core.tool.utils.CollectionUtil;
import com.xjrsoft.module.customerTwo.EMP.electricMeter.entity.TElectricMeter;
import com.xjrsoft.module.customerTwo.EMP.electricMeter.service.ITElectricMeterService;
import com.xjrsoft.third.entity.ElectricObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/api/electric_meter")
@Api(value = "电表对外写数据接口", tags = "电表对外写数据接口")
public class ElectricMeterApi {

    private final ITElectricMeterService tElectricMeterService;

    /**
     * 新增
     */
    @PostMapping("/write")
    @ApiOperation(value = "电表数据写入", notes = "电表数据写入")
    public Response write(@RequestBody Map<String,Object> data) {
        boolean flag = true;
        List<TElectricMeter> list = getList(data);
        try {
            if(CollectionUtil.isNotEmpty(list)){
                tElectricMeterService.saveBatch(list);
                tElectricMeterService.insertIgnore(list);
            }
        }catch (Exception e){
            log.error("ElectricMeterApi error",e);
        }
        return Response.ok(flag);
    }
    /**
     * 新增
     */
    @PostMapping("/test")
    @ApiOperation(value = "电表数据写入", notes = "电表数据写入")
    public Response test(@RequestBody Map<String,Object> data) {
        log.error("ElectricMeterApi Test.data: {}",data.toString());
        return Response.ok();
    }
    private List<TElectricMeter> getList(Map<String,Object> data){
        if(null != data){
            List<TElectricMeter> result = new ArrayList<>();
            String datetime = (String) data.get("datetime");
            for(String key : data.keySet()){
                if(!"datetime".equals(key)){
                    TElectricMeter one = new TElectricMeter();
                    ElectricObject object = new ObjectMapper().convertValue(data.get(key),ElectricObject.class);
                    one.setId(object.getI());
                    one.setEng(object.getV()== null||object.getV().getEng()==null ? new BigDecimal("0") : object.getV().getEng());
                    one.setDatetime(datetime.replaceAll("-|:| ",""));
                    result.add(one);
                }
            }
            return result;
        }
        return null;
    }
}
